package com.zhj.micro.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zhj.micro.order.MicroOrderApplication;
import com.zhj.micro.order.entity.Order;
import com.zhj.micro.order.entity.dto.OrderDTO;
import com.zhj.micro.order.mapper.OrderMapper;
import com.zhj.micro.order.service.OrderService;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 创建订单
     */
    @Override
    public String createOrder(OrderDTO orderDTO) {
        //1. 创建订单实体类，然后设置默认值
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString().substring(0, 6));
        order.setUpdateTime(new Date());
        order.setCreatedTime(new Date());
        //初始化商品状态
        order.setOrderStatus((byte) 0);
        BeanUtils.copyProperties(orderDTO, order);
        int insert = orderMapper.insert(order);
        //订单插入成功后，发布延时队列信息，用于检测订单是否已经支付
        if (insert > 0) {
            this.rabbitTemplate.convertAndSend("delay_order_exchange", "delay.order.1", order.getOrderId(), p -> {
                //进行消息拦截处理，给消息设置延时时间
                p.getMessageProperties().setDelay(50000);
                return p;
            });
        }
        return order.getOrderId();
    }

    /**
     * 修改订单状态
     * @param orderId
     * @return
     */
    @Override
    public boolean updateOrderStatus(String orderId, Integer status) {
        return this.orderMapper.updateStatus(orderId, status);
    }

    @Override
    public boolean checkOrder(String orderId) {
        Order order = this.orderMapper.selectOneByOrderId(orderId);
        Byte orderStatus = order.getOrderStatus();
        //订单状态小于1，证明还没有支付，将订单状态修改为 已超时
        if (orderStatus < 1) {
            this.updateOrderStatus(orderId, 4);
        }
        return true;
    }

    @Override
    public boolean payOrder(String orderId) throws JsonProcessingException {
        //1. 支付订单，修改订单后，发布库存扣除
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orderId);
        boolean b = this.updateOrderStatus(orderId, 1);
        if (b) {
            //查询出订单的信息，将订单信息发送到mq中进行库存扣减
            Order order = this.orderMapper.selectOneByOrderId(orderId);
            MessageProperties properties = MessagePropertiesBuilder
                .newInstance()
                .build();
            //将订单的实体进行序列化
            Message message = rabbitTemplate.getMessageConverter().toMessage(MicroOrderApplication.OBJECT_MAPPER.writeValueAsString(order),
                                                                             properties);
            //发送到订单队列里
            rabbitTemplate.send("product_exchange", "product.create", message);
        }
        return b;
    }

}
